/*
 *  Copyright (C) 2010 glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.bindings;

import java.lang.reflect.InvocationTargetException;
import org.balisunrise.common.BindingException;

/**
 *
 * @author Glauco
 */
public class BeansBindingSupport<T> implements BindingSupport<T>{

    private Object source;

    private String property;

    public BeansBindingSupport(Object source, String property) {
        this.source = source;
        this.property = property;
    }

    @Override
    public T getPropertyValue()
            throws BindingException, NullPointerException {
        
        T o;
        
        try {
            o = (T) BeansPropertyReader.getProperty(source, property);
        }catch(BeansPropertyReader.PropertyReaderException ex){
            throw new NullPointerException(
                    "Exception Writing source property value: "
                    + ex.getMessage());
        }catch(NullPointerException ex){
            throw ex;
        }catch(BindingException ex){
            throw ex;
        }catch(Exception ex){
            throw new BindingException(
                    "Exception reading source property value", ex);
        }

        return o;

    }

    @Override
    public void setPropertyValue(T value)
            throws BindingException, NullPointerException, Exception {

        try{
            BeansPropertyWriter.setProperty(source, property, value);
        }catch(BeansPropertyWriter.PropertyWriterException ex){
            throw new NullPointerException(
                    "Exception Writing source property value: " +
                    ex.getMessage());
        }catch(InvocationTargetException ex){
            Throwable cause = ex.getCause();
            if(cause instanceof Exception){
                throw (Exception) cause;
            }
            throw ex;
        }catch (NullPointerException ex){
            throw ex;
        }catch(BindingException ex){
            throw ex;
        } catch(Exception ex){
            throw ex;
        }

    }

}
